import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { UrlService } from './url.service';

import { Router } from '@angular/router';
import { finalize, tap } from 'rxjs/operators';
import { res } from './Interface';
import { NzMessageService } from 'ng-zorro-antd/message';
/** Pass untouched request through to the next request handler. */
@Injectable()
export class Interceptor implements HttpInterceptor {
  constructor(
    private url: UrlService,
    private router: Router,
    private message: NzMessageService
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): any {
    const token = localStorage.getItem('token');
    if (!token) {
      this.router.navigateByUrl('');
      this.message.error('请登录');
      return;
    }

    const authReq = req.clone({
      url: req.url.includes('http://')
        ? req.url
        : `${this.url.baseurl}${req.url}`,
      headers: req.headers.set('Authorization', `bearer ${token}`),
    });

    return next.handle(authReq).pipe(
      tap((event) => {
        if (event instanceof HttpResponse) {
          const { code, msg } = event.body as res;
          if (code == 0 && msg == 'The token is expired.') {
            this.router.navigateByUrl('');
            this.message.error('登录信息已过期，请重新登录');
          }
        }
      }),
      finalize(() => {})
    );
  }
}
